package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备数据信息Service业务层处理
 * 
 * @author Nuyoah
 * @date 2025-05-25
 */
@Service
@Slf4j
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据信息
     * 
     * @param id 设备数据信息主键
     * @return 设备数据信息
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据信息列表
     * 
     * @param deviceData 设备数据信息
     * @return 设备数据信息
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据信息
     * 
     * @param deviceData 设备数据信息
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据信息
     * 
     * @param deviceData 设备数据信息
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据信息
     * 
     * @param ids 需要删除的设备数据信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息信息
     * 
     * @param id 设备数据信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 将获取到的设备数据进行解析,批量保存到设备数据表中
     *
     * @param contentStr
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleMessage(String contentStr) {
        //1.判断数据是否为空
        if(StringUtils.isBlank(contentStr)){
            throw new BaseException("数据非法");
        }
        JSONObject message = JSONUtil.parseObj(contentStr);
        JSONObject notifyDataObj = message.getJSONObject("notify_data");
        if (notifyDataObj==null){
            throw new BaseException("数据非法");
        }
        JSONObject header = notifyDataObj.getJSONObject("header");
        JSONObject body = notifyDataObj.getJSONObject("body");
        if (header==null||body==null){
            throw new BaseException("数据非法");
        }

        //2.解析每一层数据
        IotMsgNotifyData notifyData = JSONUtil.toBean(notifyDataObj, IotMsgNotifyData.class);
        String deviceId = notifyData.getHeader().getDeviceId();

        //3.判断是设备是否存在
        Device device = deviceService.lambdaQuery().eq(Device::getIotId, deviceId).one();
        if (device== null){
            throw new BaseException("设备不存在,暂无该设备");
        }

        //4.设备数据封装
        List<IotMsgService> services = notifyData.getBody().getServices();
        List<DeviceData> deviceDataList = new ArrayList<>();
        services.forEach(x->{
            //获取时间,转换对应的格式
            String eventTimeStr = x.getEventTime();
            LocalDateTime eventTime = OffsetDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            Map<String, Object> properties = x.getProperties();
            properties.forEach((k,v)->{
                DeviceData deviceData = new DeviceData();
                BeanUtils.copyProperties(device,deviceData);
                deviceData.setId(null);//必须设置为空,否则批量新增时每条数据的ID会被复制成同一个ID,程序无法正常运行
                deviceData.setFunctionId(k);//功能名称(物模型的属性值)
                deviceData.setAccessLocation(device.getBindingLocation());//接入位置
                deviceData.setDataValue(String.valueOf(v));//数据值(物模型属性的值)
                deviceData.setAlarmTime(eventTime);//数据上报时间
                deviceDataList.add(deviceData);
            });

        });

        //5.批量保存数据
        if (CollUtil.isNotEmpty(deviceDataList)){
            boolean result = this.saveBatch(deviceDataList);
            if (!result){
                throw new BaseException("批量保存数据失败");
            }
            //将设备数据信息保存到Redis中
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LIST_DATA_KEY, deviceId, JSONUtil.toJsonStr(deviceDataList));
            log.info("批量保存数据成功,成功保存{}条", deviceDataList.size());
        }
    }

    /**
     * 查询设备数据信息列表
     *
     * @param dto
     * @return 设备数据信息集合
     */
    @Override
    public Page<DeviceData> pageList(DeviceDataPageReqDto dto) {
        //1.使用myBatisPlus获取分页数据
        Page<DeviceData> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        this.lambdaQuery()
                .eq(StringUtils.isNotBlank(dto.getDeviceName()), DeviceData::getDeviceName, dto.getDeviceName())
                .eq(StringUtils.isNotBlank(dto.getFunctionId()), DeviceData::getFunctionId, dto.getFunctionId())
                .eq(StringUtils.isNotBlank(dto.getDeviceId()), DeviceData::getIotId, dto.getDeviceId())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, DeviceData::getAlarmTime, dto.getStartTime(), dto.getEndTime())
                .orderByDesc(DeviceData::getAlarmTime)
                .page(page);
        //2.获取分页数据中的records数据
        List<DeviceData> deviceDataList = page.getRecords().stream().map(x -> {
            DeviceData deviceData = new DeviceData();
            BeanUtils.copyProperties(x, deviceData);
            return deviceData;
        }).collect(Collectors.toList());

        //3.封装称为Page<DeviceData>对象返回
        Page<DeviceData> deviceDataPage = new Page<>();
        deviceDataPage.setRecords(deviceDataList);
        deviceDataPage.setTotal(page.getTotal());
        return deviceDataPage;
    }
}
